﻿using JNTApp.Common;
using JNTApp.Model;
using JNTApp.util;
using Sorting.Common;
using Sorting.Model;
using Sorting.UserControl;
using Sorting.util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Sorting
{
    /// <summary>
    /// OrderListPage.xaml 的交互逻辑
    /// </summary>
    public partial class OrderListPage : Page
    {

        public OrderListPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        { 
            //BackgroundWorker,在单独的线程上执行操作
            BackgroundWorker worker = new BackgroundWorker();

            //BW.DoWork,调用BW.RunWorkerAsync()时发生

            //初始化命名委托;Lambda 运算符的左边是输入参数（如果有），右边包含表达式或语句块;
            worker.DoWork += (s, ev) =>
            {

                //for (int i = 0; i < 100; i += 10)
                //{
                //    Thread.Sleep(1000);                    
                //    //BW.ReportProgress,引发BW.ProgressChanged事件
                //    ((BackgroundWorker)s).ReportProgress(i);
                //}

                //try {
                //    PriceExcelLoader.doIt();
                //}
                //catch (Exception x){
                //    MessageBox.Show(x.Message);
                //}

                // 读取本地Excel文件列表
                List<FileInfo> fileInfos = ExcelHelper.readLocalPriceExcel("Resources\\");
                int num = 0;
                for (int i = 0; i < fileInfos.Count; i++) {
                    ((BackgroundWorker)s).ReportProgress(num += (100 / fileInfos.Count));
                    PriceExcelLoader.doIt(fileInfos[i]);
                    Thread.Sleep(100);
                }
            };
            //调用BW.ReportProgress时发生
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);

            //当后台操作已完成，被取消或引发异常时发生
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

            //BackgroundWorker.WorkerReportsProgress 获取或设置一个值，该值指示 BackgroundWorker 能否报告进度更新。
            worker.WorkerReportsProgress = true;

            //TaskbarItemInfo获取或设置 System.Windows.Window 的任务栏缩略图。
            //TaskbarItemInfo.ProgressState 获取或设置一个值，该值指示在任务栏按钮中显示进度指示器的方式。

            //TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Indeterminate;

            //TaskbarItemProgressState枚举值
            //None=0,Indeterminate=1(闪烁绿色),Normal=2(绿色),Error=3(红色),Paused=4(黄色)
            //开始执行后台操作
            worker.RunWorkerAsync();
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //ProgressChangedEventArgs.ProgressPercentage 获取异步任务的进度百分比
            ProgressBar.Value = e.ProgressPercentage;

            // double TaskbarItemInfo.ProgressValue获取或设置一个值，该值指示任务栏按钮中进度指示器的填满状态。
            //TaskbarItemInfo.ProgressValue = (double)e.ProgressPercentage / 100;
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ProgressBar.Value = 100;
            this.txtLog.Text = "加载完毕!!!";
            //TaskbarItemInfo.ProgressValue = 1.0;
        }

        public void lvwData_Loaded(object sender, RoutedEventArgs e)
        {
            btnSearch_Click(null, null);
            //PriceExcelLoader.doIt();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string kh = this.txtKH.Text;
            string cnum = this.txtCNUM.Text;
            string begin = this.txtBegin.Text;
            string end = this.txtEnd.Text;
            string zt = this.txtZT.Text;

            //((Button)sender).IsEnabled = false;
            try
            {
                string uri = Config.GetServerURL() + "/order/trans/list";

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("caccount", kh);
                dic.Add("emskind", "J-NET专线");
                dic.Add("cnum", cnum);
                dic.Add("dateb", begin);
                dic.Add("datee", end);

                string json = HttpHelper.GET(uri, dic);

                ResponseRecList<Order> r = JSONHelper.Deserialize<ResponseRecList<Order>>(json);
                if (r.ReturnValue < 0)
                {
                    MessageBox.Show(r.cMess);
                    return;
                }
                List<Order> list = r.RecList;
                if (list != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i].Idx = i + 1;
                    }
                    this.lvwData.ItemsSource = list;
                }
            }
            catch (WebException)
            {
                MessageBox.Show("查询异常");
            }
            //((Button)sender).IsEnabled = true;
        }

        private void btnSort_Click(object sender, RoutedEventArgs e)
        {
            Order item = this.lvwData.SelectedItem as Order;
            
            SortWindow win = new SortWindow();

            try
            {
                if (item != null)
                {
                    win.txtMess.Text = "运单号已确认，请在左侧扫码称重...";
                    win.txtCnum.Text = item.Cnum;
                    win.txtOrderInfo.Text = "客户:" + item.Cunitname
                        + "[" + item.Icid + "]"
                        + "\n业务日期：" + item.Ddate
                        + "\n物品描述：" + item.Cgoods
                        + "\n托运备注：" + item.Ctransnote
                        + "\n数量：" + item.Iquantity
                        + "\n快递类别：" + item.Cemskind
                        + "\n目的地：" + item.Cdes
                        + "\n收件人：" + item.Creceiver;
                    win.txtSZ.Focus();
                    win.ShowDialog();
                }
                else
                {
                    win.txtMess.Text = "等待扫描运单号...";
                    win.txtCnum.Focus();
                    win.ShowDialog();
                }
            }
            catch (Exception) {
                MessageBox.Show("通信异常");
            }
        }

        private void lvwData_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            btnSort_Click(null,null);
        }
    }
}
